<template>
    <div class="main">
        <div class="topTitle">{{ props.title }}</div>
        <div class="form_content">
            <NScrollbar>
                <NSpin :show="spinShow">
                    <div class="content">
                        <NSpace>
                            <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules"
                                :label-width="100" :model="formValue">
                                <NFormItem label="名称:" path="name">
                                    <NInput class="commonWidth" v-model:value="formValue.name" placeholder="输入名称"
                                        :allow-input="stopNull" />
                                </NFormItem>
                                <NFormItem label="类型:" path="linkType">
                                    <NSelect class="commonWidth" placeholder="请选择类型" v-model:value="formValue.linkType"
                                        :options="[
                                            { label: '藏品', value: '1' },
                                            { label: 'OA', value: '2' }
                                        ]"></NSelect>
                                </NFormItem>
                                <NFormItem label="状态:" path="linkStatus">
                                    <NSelect class="commonWidth" placeholder="请选择状态" v-model:value="formValue.linkStatus"
                                        :options="[
                                            { label: '启用', value: 1 },
                                            { label: '禁用', value: 2 }
                                        ]"></NSelect>
                                </NFormItem>
                                <NFormItem label="URL:" path="url">
                                    <NInput class="commonWidth" v-model:value="formValue.url" placeholder="输入URL"
                                        :allow-input="stopNull" />
                                </NFormItem>
                                <NFormItem label="备注:" path="remarks">
                                    <NInput class="commonWidth" v-model:value="formValue.remarks" type="textarea"
                                        style="min-height: 130rem" placeholder="输入备注" :allow-input="stopNull" />
                                </NFormItem>
                                <NFormItem label="上传图标:" path="fileId">
                                    <NUpload :max="1" :custom-request="(e: any) => commonUpload(e)" @remove="commonRemove"
                                        :default-file-list="imgList" accept="image/*" list-type="image-card"></NUpload>
                                </NFormItem>
                            </NForm>
                        </NSpace>
                    </div>
                </NSpin>
            </NScrollbar>
        </div>
    </div>
    <FixedAction>
        <NSpace justify="center">
            <NButton ghost @click="goBack" style="width: 78px;">
                取消
            </NButton>
            <NButton type="primary" @click="confirm" style="width: 78px;">
                保存
            </NButton>
        </NSpace>
    </FixedAction>
    <NModal :auto-focus="false" v-model:show="modalVisible">
        <VDialogContent @close="modalVisible = false" @submit="againConfirm" title="保存提示">
            <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
                您确定要保存吗?
            </div>
        </VDialogContent>
    </NModal>
</template>
  
<script setup lang="ts">
import { ref, watch, watchEffect } from 'vue'
import {
    NSpace,
    NForm,
    NInput,
    NFormItem,
    NButton,
    useMessage,
    NScrollbar,
    NUpload,
    NSpin,
    NModal,
    NSelect
} from 'naive-ui'
import type { FormInst } from 'naive-ui'
import type { UploadFileInfo, UploadCustomRequestOptions } from 'naive-ui'
import router from '@/router'
import { useRoute } from 'vue-router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'

const message = useMessage()
const route = useRoute()
const tags = useTagStore().tags
const props = defineProps({
    id: {
        type: [Number, String]
    },
    title: { type: String, default: () => '移动端自定义常用配置链接新增' },
})

//去除空格
const stopNull = (value: string) => {
    return !value.startsWith(' ') && !value.endsWith(' ')
}

const formRef = ref<FormInst | null>(null)
const formValue: any = ref({
    name: null,
    url: null,
    fileId: null,
    remarks: null,
    linkType: null,
    linkStatus: null
})
const rules: any = {
    name: {
        required: true,
        trigger: ['input', 'blur'],
        validator: (_: any, value: any) => {
            if (!value) return new Error('请输入名称')
            if (value.length > 10) return new Error('名称字数不得超过10')
            return true
        }
    },
    linkType: {
        required: true,
        message: '请选择类型',
        trigger: ['change', 'blur']
    },
    linkStatus: {
        type: 'any',
        required: true,
        message: '请选择状态',
        trigger: ['change', 'blur']
    },
    url: {
        required: true,
        trigger: ['input', 'blur'],
        validator: (_: any, value: any) => {
            if (!value) return new Error('请输入url')
            if (value.length > 100) return new Error('url字数不得超过100')
            return true
        }
    },
    remarks: {
        required: true,
        trigger: ['input', 'blur'],
        validator: (_: any, value: any) => {
            if (!value) return new Error('请输入备注')
            if (value.length > 100) return new Error('备注字数不得超过100')
            return true
        }
    },
    fileId: {
        required: true,
        message: '请上传图标',
        trigger: ['change', 'blur']
    }
}
//文件上传
const imgHZ = ['jpg', 'png', 'jpeg']
const imgList = ref<UploadFileInfo[]>([])
const tasmpList = ref<any>([])
const commonUpload = async ({ file, onFinish, onError }: UploadCustomRequestOptions) => {
    const tmp = file.name.split('.')
    if (!imgHZ.includes(tmp[tmp.length - 1])) return message.error('请上传图片类型'), onError()
    const fileData = new FormData()
    fileData.append('file', file.file as File)
    const [error, res] = await sendRequest<HttpResponse>({
        module: 'upload',
        api: 'uploadFile',
        override: {
            data: {
                file: fileData.get('file')
            }
        }
    })
    if (error) return message.error(error.message), onError()
    tasmpList.value.push({
        id: res.data.fileId,
        name: res.data.name,
        status: 'finished',
        url: res.data.url
    })
    message.success('上传成功')
    formValue.value.fileId = res.data.fileId
    formRef.value?.validate()
    onFinish()
}
// 删除附件
async function commonRemove() {
    tasmpList.value = []
    formValue.value.fileId = ''
    message.success('删除附件成功')
}
//自定义配置信息
const spinShow = ref(false)
const fileList: any = ref([])
const getInfo = async () => {
    spinShow.value = true
    const [error, res] = await sendRequest({
        module: 'office',
        api: 'mobileLinkInfo',
        uri: {
            id: route.query?.id as never
        }
    })
    if (error) return message.error(error.message)
    const tmp: any = res.data
    Object.keys(formValue.value).map((it: any) => {
        formValue.value[it] = res.data[it]
    })
    fileList.value = tmp.fileList
    spinShow.value = false
}
// 监听附件
watchEffect(() => {
    if (imgList.value.length && fileList.value?.length) {
        tasmpList.value.splice(0, imgList.value.length)
        imgList.value.splice(0, imgList.value.length)
        fileList.value.map((it: any) => {
            imgList.value.push({
                id: it.id,
                name: it.name,
                status: 'finished',
                url: it.path
            })
            tasmpList.value.push({
                id: it.id,
                name: it.name,
                status: 'finished',
                url: it.path
            })
        })
    } else {
        fileList.value.map((it: any) => {
            imgList.value.push({
                id: it.id,
                name: it.name,
                status: 'finished',
                url: it.path
            })
            tasmpList.value.push({
                id: it.id,
                name: it.name,
                status: 'finished',
                url: it.path
            })
        })
    }
})
// 返回
const goBack = () => {
    const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
    tags.splice(index, 1)
    router.push({ path: '/OA/Office/H5CustomSetting' })
}
// 确定
const modalVisible = ref(false)
const confirm = () => {
    formRef.value?.validate(async (err: any) => {
        if (err) return
        modalVisible.value = true
    })
}
// 新增
const againConfirm = async () => {
    if (!route.query?.id) {
        const [error, res] = await sendRequest<HttpResponse>({
            module: 'office',
            api: 'mobileLinkSave',
            override: {
                data: {
                    ...formValue.value
                }
            }
        })
        if (error) return message.error(error.message)
        if (res.code !== 0) return message.error(res.msg)
        message.success(res.msg)
        goBack()
    } else {
        const [error, res] = await sendRequest<HttpResponse>({
            module: 'office',
            api: 'mobileLinkUpdate',
            override: {
                data: {
                    id: route.query?.id,
                    ...formValue.value
                }
            }
        })
        if (error) return message.error(error.message)
        if (res.code !== 0) return message.error(res.msg)
        message.success(res.msg)
        modalVisible.value = false
        goBack()
    }
}

watch(
    () => route.query?.id,
    () => {
        if (route.query?.id && props.title == "移动端自定义常用配置链接编辑") getInfo()
    },
    { deep: true, immediate: true }
)
</script>
  
<style scoped lang="scss">
@mixin CommonFont {
    font-size: 16rem;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
    width: 360rem;
}

.main {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    overflow: hidden;

    .topTitle {
        width: 100%;
        height: 64rem;
        border-bottom: 1px solid #fff;
        padding: 20rem;
        margin-bottom: 20rem;
        @include CommonFont;
    }

    .form_content {
        width: 100%;
        height: 100%;
        padding: 20rem 20rem 0;

        .content {
            display: flex;
            align-items: center;
            flex-direction: column;
            width: 100%;
            height: 100%;
            padding: 18rem 33rem 120rem;
            overflow-y: scroll;
            background-color: #ebeceb;

            .scope {
                width: 360rem;
                height: 130rem;
                background: #e1e1e1;
                margin-bottom: 25rem;
            }
        }
    }
}

.content::-webkit-scrollbar {
    display: none;
}

:deep(.n-spin-container) {
    width: 100%;
    height: 100%;
}

:deep(.n-scrollbar-container) {
    width: 100%;
    height: 100%;
}

:deep(.n-scrollbar-content) {
    width: 100%;
    height: 100%;
}

:deep(.n-spin-content) {
    width: 100%;
    height: 100%;
}
</style>
  